#include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

extern sqlite3 *ppDb;

void init_sqlite3()
{
	if (sqlite3_open("userinfo.db", &ppDb) != SQLITE_OK)
	{
		printf("sqlite3_open error %s\n", sqlite3_errmsg(ppDb));
		exit(1);
	}

	char sql[128] = {0};

	sprintf(sql, "create table if not exists user (username text, password text)");
	if (sqlite3_exec(ppDb, sql, NULL, NULL, NULL) != SQLITE_OK)
	{
		printf("sqlite3_exec error %s\n", sqlite3_errmsg(ppDb));
		return;
	}

}

int sqlite3_user_exist(const char *name)
{
	char sql[128] = {0};
	char **result;
	int row, column;
	char *errmsg;

	sprintf(sql, "select username from user;");

	if (sqlite3_get_table(ppDb, sql, &result, &row, &column, &errmsg) != SQLITE_OK)
	{
		printf("sqlite3_get_table error %s\n", errmsg);
		return 1;
	}

	for (int i = 0; i < row; i++)
	{
		if (!strcmp(result[i + column], name))
			return 1;
	}

	sqlite3_free_table(result);
	
	return 0;
}

void database_insert_user(const char *u, const char *p)
{
	char sql[128] = {0};

	sprintf(sql, "insert into user values ('%s', '%s');", u, p);

	if (sqlite3_exec(ppDb, sql, NULL, NULL, NULL) != SQLITE_OK)
	{
		printf("sqlite3_exec error %s\n", sqlite3_errmsg(ppDb));
	}
}

int database_password_correct(const char *u, const char *p)
{
	char sql[128] = {0};
	char **result;
	int row, column, flag = 0;
	char *errmsg;

	sprintf(sql, "select password from user where username = '%s';", u);

	if (sqlite3_get_table(ppDb, sql, &result, &row, &column, &errmsg) != SQLITE_OK)
	{
		printf("sqlite3_get_table error %s\n", errmsg);
		return 1;
	}

	if (!strcmp(result[1], p))
	{
		flag = 1;
	}

	sqlite3_free_table(result);
	
	return flag;

}

